package com.autotest.nore.controller;

import com.autotest.nore.common.exception.TokenEmptyException;
import com.autotest.nore.common.utils.PageUtils;
import com.autotest.nore.common.utils.Pager;
import com.autotest.nore.dto.PlanDTO;
import com.autotest.nore.request.QueryRequest;
import com.autotest.nore.service.PlanService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/autotest/plan")
public class PlanController {

    @Resource
    private PlanService planService;

    @PostMapping("/save")
    public void savePlan(@RequestBody PlanDTO planDTO, HttpServletRequest request) {
        HttpSession session = request.getSession(false); // 获取会话，如果不存在则返回null
        if (session == null || session.getAttribute("userName") == null) {
            throw new TokenEmptyException("用户未登录，请重新登录");
        }
        String userName = session.getAttribute("userName").toString();
        planDTO.setUpdateUser(userName);
        planService.savePlan(planDTO);
    }

    @PostMapping("/delete")
    public void deletePlan(@RequestBody PlanDTO planDTO) {
        planService.deletePlan(planDTO);
    }

    @GetMapping("/detail/{planId}")
    public PlanDTO getPlanDetail(@PathVariable String planId){
        return planService.getPlanDetail(planId);
    }

    @PostMapping("/list/{goPage}/{pageSize}")
    public Pager<List<PlanDTO>> getPlanList(@PathVariable int goPage, @PathVariable int pageSize,
                                            @RequestBody QueryRequest request) {
        Page<Object> page = PageHelper.startPage(goPage, pageSize, true);
        return PageUtils.setPageInfo(page, planService.getPlanList(request));
    }
}
